﻿using Models;
using QRCoder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace CommTestNFW.ImageCode
{
    public class CodeHepler
    {
        public static string path = LabelConfig.BasePath;

        static readonly int width = LabelConfig.PageWidth;
        static readonly int height = LabelConfig.PageHeight;

        static int pageNo = 1;
        public static List<string> Build(IEnumerable<PrintLabNo> codes = null)
        {
            if (codes == null || !codes.Any())
                codes = DataHelper.GetPrintLabNos(576);

            pageNo = 1;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //var codes = DataHelper.GetPrintLabNos(216);
            //一次打印,  5张单排打印,  6张双排打印
            //双排：96*6=576个编码
            //单排：216 * 3 = 648个编码（两张半的样子）
            //单排的要两份   2 * 3 = 6

            var pages1 = DataHelper.GetDoublePages(codes.ToArray());
            var pages2 = DataHelper.GetPages(codes.ToArray());

            List<CodePage> codePages1 = GetCodePages(pages1);
            List<CodePage> codePages2 = GetCodePages(pages2);
            var codePages = codePages1.Concat(codePages2);

            codePages.AsParallel().ForAll(Build);

            //根据生成顺序返回image
            return codePages.OrderBy(s => s.Id).Select(s => s.ImagePath).ToList();
        }

        private static List<CodePage> GetCodePages(List<List<PrintLabNo>> pages1)
        {
            List<CodePage> images = new List<CodePage>();
            foreach (var codes in pages1)
            {
                //构建页面对象
                var page = new CodePage(width, height);
                page.Id = pageNo++;
                page.ImagePath = $"{path}/test-{codes.FirstOrDefault().LabNo}.jpg";
                page.OriginImagePath = $"{path}/test-origin-{codes.FirstOrDefault().LabNo}.jpg";
                page.SetCode(codes);
                Build(page);
            }
            return images;
        }


        private static void Build(CodePage page)
        {
            Bitmap bitmap = new Bitmap(width, height);

            //构建绘图对象
            using (var gm = GraphicsManagement.Build(bitmap))
            {
                //打印单双排角标
                if (LabelConfig.DoublePrintFlag && page.DoublePage)
                {
                    int border = 6;
                    //上边框
                    gm.Graphics.FillRectangle(gm.BrushRed, new RectangleF(0, 0, width, border));
                    //下边框
                    gm.Graphics.FillRectangle(gm.BrushRed, new RectangleF(0, height - border, width, border));
                    //右边框
                    gm.Graphics.FillRectangle(gm.BrushRed, new RectangleF(width - border, 0, border, height));
                    //左边框
                    gm.Graphics.FillRectangle(gm.BrushRed, new RectangleF(0, 0, border, height));
                }

                foreach (var label in page.CodeLabels)
                {
                    //draw background
                    gm.Graphics.FillRectangle(gm.BrushWhite, new RectangleF(label.Point, label.Size));

                    MakeCode(gm, label);
                }
            }
            bitmap.Save(page.OriginImagePath);
            bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
            bitmap.Save(page.ImagePath);
            bitmap.Dispose();
        }

        public static void MakeCode(GraphicsManagement gm, CodeLabel label)
        {
            var code = label.Code;
            if (!string.IsNullOrWhiteSpace(code))
            {
                Brush brush = label.Brush;
                Graphics g = gm.Graphics;
                Font font = gm.Font;

                var size = label.Size;
                LineText line1 = label.Line1Text;
                LineText line2 = label.Line2Text;
                //字母的长度
                var size1 = g.MeasureString(line1.Text, font);
                var size2 = g.MeasureString(line2.Text, font);
                //偏移量
                var offset1 = (size - size1).Width / 2 + 1;// 像素是整数, 对于小数会四舍五入, +1整数偏移
                var offset2 = (size - size2).Width / 2 + 1;
                var p = label.Point;
                var p1 = new PointF(p.X + offset1, p.Y + 8);
                var p2 = new PointF(p.X + offset2, p.Y + 20 + 12);
                g.DrawString(line1.Text, font, brush, p1);
                g.DrawString(line2.Text, font, brush, p2);

                var qrCode = label.QrCode;
                var pInner = label.InnerPoint;
                Bitmap codeImage = MakeQrCode(code);
                var codePy = pInner.Y + label.InnerSize.Height - qrCode.Height;
                g.DrawImage(codeImage, new RectangleF(pInner.X, codePy, qrCode.Width, qrCode.Height));
            }
        }


        public static Bitmap MakeQrCode(string code, int pixel = 72)
        {
            QRCodeGenerator generator = new QRCodeGenerator();

            QRCodeData qRCodeData = generator.CreateQrCode(code, QRCodeGenerator.ECCLevel.H);
            QRCode qRCode = new QRCode(qRCodeData);
            return qRCode.GetGraphic(pixel, Color.Black, Color.White, false);
        }

    }
}
